package com.liuyucheng.util.m4s;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class VideoAudioMerger {

    /**
     * 合并视频和音频文件
     * @param videoPath 视频文件路径
     * @param audioPath 音频文件路径
     * @param outputPath 输出文件路径
     */
    public static void mergeVideoAndAudio(String videoPath, String audioPath, String outputPath) {
        try {
            // 构建FFmpeg命令
            // 假设audioPath是一个纯音频文件（如mp3），videoPath是一个视频文件（如mp4，但没有或不需要其音频）
            // -i 指定输入文件，-c:v copy 表示视频编解码器复制，不重新编码，-c:a aac 指定音频编解码器为aac，-shortest 表示输出文件的持续时间由最短的输入流决定
            String command = "ffmpeg -i " + videoPath + " -i " + audioPath + " -c:v copy -c:a aac " + outputPath;

            System.out.println("执行合并命令 = " + command);
            System.out.println("处理中...");
            // 执行FFmpeg命令
            ProcessBuilder pb = new ProcessBuilder("ffmpeg", "-i", videoPath, "-i", audioPath, "-c:v", "copy", "-c:a", "aac", outputPath);
            pb.redirectErrorStream(true); // 将stderr合并到stdout
            Process process = pb.start();
            // 读取合并后的stdout/stderr
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            int count = 0;
            while ((line = reader.readLine()) != null) {
                System.out.print(" " + count++); // 处理或打印输出
            }

            // 等待FFmpeg命令执行完成
            int exitVal = process.waitFor();
            if (exitVal == 0) {
                System.out.println("合并成功!");
            } else {
                // 错误处理
                System.out.println("合并出错!");
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        //ffmpeg –version
        String videoPath = "D:\\MSI\\Download\\36003632_sr2-1-100035.mp4";
        String audioPath = "D:\\MSI\\Download\\36003632_p1-1-30280.mp4";
        String outputPath = "D:\\MSI\\Download\\output.mp4";

        mergeVideoAndAudio(videoPath, audioPath, outputPath);
    }
}